/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.bloginfo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.base.entity.BaseEntity;
import vip.xiaonuo.core.pojo.login.SysLoginUser;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.modular.bloginfo.entity.BlogInfo;
import vip.xiaonuo.modular.bloginfo.enums.BlogInfoExceptionEnum;
import vip.xiaonuo.modular.bloginfo.mapper.BlogInfoMapper;
import vip.xiaonuo.modular.bloginfo.param.BlogInfoParam;
import vip.xiaonuo.modular.bloginfo.service.BlogInfoService;
import vip.xiaonuo.sys.modular.role.service.SysRoleService;

import java.util.List;

/**
 * 博客信息表service接口实现类
 *
 * @author 刘文理
 * @date 2021-07-09 09:20:28
 */
@Service
public class BlogInfoServiceImpl extends ServiceImpl<BlogInfoMapper, BlogInfo> implements BlogInfoService {
    @Autowired
    private BlogInfoMapper blogInfoMapper;
    @Autowired
    private SysRoleService sysUserDataScopeService;

    @Override
    public PageResult<BlogInfo> page(BlogInfoParam blogInfoParam) {
        QueryWrapper<BlogInfo> queryWrapper = new QueryWrapper<>();
        SysLoginUser user = LoginContextHolder.me().getSysLoginUserUpToDate();
        //查询过滤，只能查自己的数据
        if (user.getAdminType() != 1) {
            queryWrapper.lambda().eq(BlogInfo::getCreateUser, user.getId());
        }
        if (ObjectUtil.isNotNull(blogInfoParam)) {
            // 根据博客标题 查询
            if (ObjectUtil.isNotEmpty(blogInfoParam.getBlogTitle())) {
                queryWrapper.lambda().like
                        (BlogInfo::getBlogTitle, blogInfoParam.getBlogTitle());
            }
            // 根据博客自定义路径url 查询
            if (ObjectUtil.isNotEmpty(blogInfoParam.getBlogSubUrl())) {
                queryWrapper.lambda().eq
                        (BlogInfo::getBlogSubUrl, blogInfoParam.getBlogSubUrl());
            }
            // 根据博客前言 查询
            if (ObjectUtil.isNotEmpty(blogInfoParam.getBlogPreface())) {
                queryWrapper.lambda().eq
                        (BlogInfo::getBlogPreface, blogInfoParam.getBlogPreface());
            }
            // 根据博客内容 查询
            if (ObjectUtil.isNotEmpty(blogInfoParam.getBlogContent())) {
                queryWrapper.lambda().eq
                        (BlogInfo::getBlogContent, blogInfoParam.getBlogContent());
            }
            // 根据博客分类id 查询
            if (ObjectUtil.isNotEmpty(blogInfoParam.getBlogCategoryId())) {
                queryWrapper.lambda().eq
                        (BlogInfo::getBlogCategoryId, blogInfoParam.getBlogCategoryId());
            }
            // 根据博客分类(冗余字段) 查询
            if (ObjectUtil.isNotEmpty(blogInfoParam.getBlogCategoryName())) {
                queryWrapper.lambda().eq
                        (BlogInfo::getBlogCategoryName, blogInfoParam.getBlogCategoryName());
            }
            // 根据博客标签(冗余字段) 查询
            if (ObjectUtil.isNotEmpty(blogInfoParam.getBlogTags())) {
                queryWrapper.lambda().eq
                        (BlogInfo::getBlogTags, blogInfoParam.getBlogTags());
            }
            // 根据0-草稿 1-发布 查询
            if (ObjectUtil.isNotEmpty(blogInfoParam.getBlogStatus())) {
                queryWrapper.lambda().eq
                        (BlogInfo::getBlogStatus, blogInfoParam.getBlogStatus());
            }
            // 根据阅读量 查询
            if (ObjectUtil.isNotEmpty(blogInfoParam.getBlogViews())) {
                queryWrapper.lambda().eq
                        (BlogInfo::getBlogViews, blogInfoParam.getBlogViews());
            }
            // 根据0-允许评论 1-不允许评论 查询
            if (ObjectUtil.isNotEmpty(blogInfoParam.getEnableComment())) {
                queryWrapper.lambda().eq
                        (BlogInfo::getEnableComment, blogInfoParam.getEnableComment());
            }
            // 根据是否删除 0=否 1=是 查询
            if (ObjectUtil.isNotEmpty(blogInfoParam.getIsDeleted())) {
                queryWrapper.lambda().eq
                        (BlogInfo::getIsDeleted, blogInfoParam.getIsDeleted());
            }
            // 根据点赞数 查询
            if (ObjectUtil.isNotEmpty(blogInfoParam.getLikeNum())) {
                queryWrapper.lambda().eq
                        (BlogInfo::getLikeNum, blogInfoParam.getLikeNum());
            }
            queryWrapper.lambda().orderByDesc(BlogInfo::getCreateTime);
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    @Cacheable(cacheNames = "vip.xiaonuo.modular.bloginfo.service.impl.BlogInfoServiceImpl.pubPage", key = "#blogInfoParam")
    public PageResult<BlogInfo> pubPage(BlogInfoParam blogInfoParam) {
        QueryWrapper<BlogInfo> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(blogInfoParam)) {
            queryWrapper.lambda().orderByDesc(BlogInfo::getIsTop);
            queryWrapper.lambda().orderByDesc(BlogInfo::getIsRecommend);
            queryWrapper.lambda().orderByDesc(BlogInfo::getCreateTime);
            // 根据博客标题 查询
            if (ObjectUtil.isNotEmpty(blogInfoParam.getBlogTitle())) {
                queryWrapper.lambda().like
                        (BlogInfo::getBlogTitle, blogInfoParam.getBlogTitle());
            }
            // 根据博客自定义路径url 查询

            // 根据博客前言 查询

            // 根据博客内容 查询

            // 根据博客分类id 查询

            // 根据博客分类(冗余字段) 查询
            if (ObjectUtil.isNotEmpty(blogInfoParam.getBlogCategoryName())) {
                queryWrapper.lambda().eq
                        (BlogInfo::getBlogCategoryName, blogInfoParam.getBlogCategoryName());
            }
            // 根据博客标签(冗余字段) 查询
            if (ObjectUtil.isNotEmpty(blogInfoParam.getBlogTags())) {
/*                queryWrapper.lambda().eq
                        (BlogInfo::getBlogTags, blogInfoParam.getBlogTags());*/
                queryWrapper.lambda().like(BlogInfo::getBlogTags, blogInfoParam.getBlogTags());
            }
            // 根据0-草稿 1-发布 查询

            // 根据阅读量 查询

            // 根据0-允许评论 1-不允许评论 查询

            // 根据是否删除 0=否 1=是 查询

            // 根据点赞数 查询

            queryWrapper.lambda().select(BlogInfo::getBlogId, BlogInfo::getBlogTitle, BlogInfo::getBlogSubUrl, BlogInfo::getBlogPreface, BlogInfo::getBlogCategoryId,
                    BlogInfo::getBlogCategoryName, BlogInfo::getBlogViews, BlogInfo::getBlogTags, BlogInfo::getBlogStatus, BlogInfo::getLikeNum, BlogInfo::getIsRecommend,
                    BlogInfo::getIsTop, BlogInfo::getBanner, BlogInfo::getCreateTime, BlogInfo::getUpdateTime, BlogInfo::getEnableComment)
                    .eq(BlogInfo::getBlogStatus, 1)
                    .orderByDesc(BlogInfo::getCreateTime);
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<BlogInfo> list(BlogInfoParam blogInfoParam) {
        return this.list();
    }

    @Override
    public void add(BlogInfoParam blogInfoParam) {
        BlogInfo blogInfo = new BlogInfo();
        BeanUtil.copyProperties(blogInfoParam, blogInfo);
        this.save(blogInfo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(BlogInfoParam blogInfoParam) {
        this.removeById(blogInfoParam.getBlogId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean edit(BlogInfoParam blogInfoParam) {
        BlogInfo blogInfo = this.queryBlogInfo(blogInfoParam);
        SysLoginUser user = LoginContextHolder.me().getSysLoginUserUpToDate();
        if (user.getAdminType() != 1) {
            if (!blogInfo.getCreateUser().equals(user.getId())) {
                return false;
            }
        }
        BeanUtil.copyProperties(blogInfoParam, blogInfo);
        this.updateById(blogInfo);
        return true;
    }

    @Override
    public BlogInfo detail(BlogInfoParam blogInfoParam) {
        return this.queryBlogInfo(blogInfoParam);
    }

    @Override
    public boolean blogStatusToggle(BlogInfoParam blogInfoParam) {
        LambdaQueryWrapper<BlogInfo> wrapper = new QueryWrapper<BlogInfo>()
                .lambda()
                .eq(BlogInfo::getBlogId, blogInfoParam.getBlogId())
                .select(BlogInfo::getBlogId, BlogInfo::getBlogStatus, BlogInfo::getCreateUser);
        BlogInfo blogInfo = this.list(wrapper).get(0);
        if (!judge(blogInfo)) {
            return false;
        }
        blogInfo.setBlogStatus(blogInfo.getBlogStatus() == 0 ? 1 : 0);
        return this.update(blogInfo, wrapper);
    }

    @Override
    public boolean enableCommentToggle(BlogInfoParam blogInfoParam) {
        LambdaQueryWrapper<BlogInfo> wrapper = new QueryWrapper<BlogInfo>()
                .lambda()
                .eq(BlogInfo::getBlogId, blogInfoParam.getBlogId())
                .select(BlogInfo::getBlogId, BlogInfo::getEnableComment, BlogInfo::getCreateUser);
        BlogInfo blogInfo = this.list(wrapper).get(0);
        if (!judge(blogInfo)) {
            return false;
        }
        blogInfo.setEnableComment(blogInfo.getEnableComment() == 0 ? 1 : 0);
        return this.update(blogInfo, wrapper);
    }

    @Override
    public boolean isDeletedToggle(BlogInfoParam blogInfoParam) {
        LambdaQueryWrapper<BlogInfo> wrapper = new QueryWrapper<BlogInfo>()
                .lambda()
                .eq(BlogInfo::getBlogId, blogInfoParam.getBlogId())
                .select(BlogInfo::getBlogId, BlogInfo::getIsDeleted, BlogInfo::getCreateUser);
        BlogInfo blogInfo = this.list(wrapper).get(0);
        if (!judge(blogInfo)) {
            return false;
        }
        blogInfo.setIsDeleted(blogInfo.getIsDeleted() == 0 ? 1 : 0);
        return this.update(blogInfo, wrapper);
    }

    @Override
    public boolean isRecommendToggle(BlogInfoParam blogInfoParam) {
        LambdaQueryWrapper<BlogInfo> wrapper = new QueryWrapper<BlogInfo>()
                .lambda()
                .eq(BlogInfo::getBlogId, blogInfoParam.getBlogId())
                .select(BlogInfo::getBlogId, BlogInfo::getIsRecommend, BlogInfo::getCreateUser);
        BlogInfo blogInfo = this.list(wrapper).get(0);
        if (!judge(blogInfo)) {
            return false;
        }
        if (blogInfo.getIsRecommend() != null) {
            blogInfo.setIsRecommend(blogInfo.getIsRecommend() == 0 ? 1 : 0);
        } else {
            blogInfo.setIsRecommend(0);
        }

        return this.update(blogInfo, wrapper);
    }

    @Override
    public boolean isTopToggle(BlogInfoParam blogInfoParam) {
        LambdaQueryWrapper<BlogInfo> wrapper = new QueryWrapper<BlogInfo>()
                .lambda()
                .eq(BlogInfo::getBlogId, blogInfoParam.getBlogId())
                .select(BlogInfo::getBlogId, BlogInfo::getIsTop, BlogInfo::getCreateUser);
        BlogInfo blogInfo = this.list(wrapper).get(0);
        if (!judge(blogInfo)) {
            return false;
        }
        if (blogInfo.getIsTop() != null) {
            blogInfo.setIsTop(blogInfo.getIsTop() == 0 ? 1 : 0);
        } else {
            blogInfo.setIsTop(0);
        }
        return this.update(blogInfo, wrapper);
    }

    /**
     * 获取博客信息表
     *
     * @author 刘文理
     * @date 2021-07-09 09:20:28
     */
    private BlogInfo queryBlogInfo(BlogInfoParam blogInfoParam) {
        BlogInfo blogInfo = this.getById(blogInfoParam.getBlogId());
        if (ObjectUtil.isNull(blogInfo)) {
            throw new ServiceException(BlogInfoExceptionEnum.NOT_EXIST);
        }
        return blogInfo;
    }

    private boolean judge(BaseEntity entity) {
        SysLoginUser user = LoginContextHolder.me().getSysLoginUserUpToDate();
        if (user.getAdminType() != 1) {
            if (!entity.getCreateUser().equals(user.getId())) {
                return false;
            }
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "vip.xiaonuo.modular.bloginfo.service.impl.BlogInfoServiceImpl.getOne", key = "#blogId")
    public BlogInfo getOne(String blogId, Boolean throwEx) {
        QueryWrapper<BlogInfo> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(BlogInfo::getBlogId, blogId);
        if (throwEx) {
            return baseMapper.selectOne(wrapper);
        }
        return SqlHelper.getObject(log, baseMapper.selectList(wrapper));
    }

    @Override
    public void view(String blogId) {
        blogInfoMapper.view(blogId);
    }

}
